import {getUserInfo, loginPassword} from '/@/api';
import {useCookies} from '@vueuse/integrations/useCookies';
import {defineStore} from 'pinia';
// import { getUserInfo, loginPassword } from '/@/api'
// import { useUserStore } from "/src/store/modules/user";

const {VITE_TOKEN_KEY} = import.meta.env;
const token = useCookies().get(VITE_TOKEN_KEY as string);
const ryid = localStorage.getItem('ryid')

import {useRouter} from 'vue-router';

// const router = useRouter();

interface StoreUser {
    token: string;
    info: Record<any, any>;
    userType: '';    //0学生 1老师
    freeTestInfo: {}
}

export const useUserStore = defineStore({
    id: 'app-user',
    state: (): StoreUser => ({
        // token: token,
        loginToken: localStorage.getItem('loginToken'),
        token: localStorage.getItem('token') || '',
        info: localStorage.getItem('USERINFO') || {} as Record<any, any>,
        userType: '',
        router: useRouter(),
        freeTestInfo: {},
        roleId: '', // 当前角色 id
    }),
    getters: {
        getUserInfo(): any {
            return this.info || {};
        },
        getUserType(): any {
            return this.userType || '';
        },
        getUserToken(): any {
            return this.token || '';
        },
        getUserLoginToken(): any {
            return this.loginToken || '';
        },
        getFreeTestInfo(): any {
            return this.freeTestInfo || '';
        },
    },
    actions: {
        setInfo(info: any, type: any) {
            this.info = info ? info : '';
            localStorage.setItem('USERINFO', JSON.stringify(info));
            /*localStorage.setItem('specialName',info.specialName);
            localStorage.setItem('year', info.year);
            localStorage.setItem()*/
            console.log('setInfo', info)
            /*console.log('userType',type
            +
            )
            console.log('ryid',info[type])*/
            /*if(null != type) localStorage.setItem('ryid',info[type].id)
            else localStorage.setItem('ryid',info[this.userType].id)*/
        },
        setUserType(userType: any) {
            this.userType = userType ? userType : '';
        },
        setUserToken(token: any) {
            localStorage.setItem('token', token)
            console.log('setUserToken:', localStorage.getItem('token'))
            this.token = token ? token : '';
        },
        setUserLoginToken(loginToken: any) {
            localStorage.setItem('loginToken', loginToken)
            this.loginToken = loginToken ? loginToken : '';
        },
        setFreeTestInfo(freeTestInfo: any): any {
            return this.freeTestInfo = freeTestInfo || '';
        },
        login() {
            return new Promise((resolve) => {
                const {execute} = loginPassword();
                execute().then((res) => {
                    this.setInfo(res);
                    resolve(res);
                });
            });
        },
        async relogin() {
            // const token = localStorage.getItem('token')
            // const
            const userStore = useUserStore();
            console.log('token', userStore.getUserLoginToken)
            const res = await getUserInfo(userStore.getUserLoginToken);
            let info = res.response.value.extend
            console.log('info', info)
            // let userInfo = info.USER.replace(/\\/g,'')
            // let userJson = JSON.parse(userInfo)
            // 存储
            // userStore.setInfo(info,'stud')
            // this.userStore.setUserType(0)
            // this.router.push('/home');
            userStore.setUserType(info.TYPE)
            if (info.TYPE == 'stud') {
                userStore.setInfo(info.userInfo, info.TYPE)
                // this.userStore.setUserType(0)
                this.router.push('/mainMenu');
            } else if (info.TYPE == 'tea') {
                // this.userStore.setUserType(1)
                this.router.push('/mainMenu_tea');
            } else {
                //身份信息错误
                alert('身份信息错误')
            }
        }
    },
    persist: {
        key: 'token',
        storage: localStorage,
        paths: ['token'],
    },
});
// export const useUserStore = defineStore('app-user', () => {
//   const Token = ref(token);
//   const info = ref<Record<any, any>>({});
//   const setInfo = (info: any) => {
//     info.value = info ? info : '';
//   };
//   const getUserInfo = () => {
//     return info || {};
//   };
//   const login = () => {
//     return new Promise((resolve) => {
//       const { data } = loginPassword();
//       watch(data, () => {
//         setInfo(data.value);
//         // useCookies().set(VITE_TOKEN_KEY as string, data.value.token);
//         resolve(data.value);
//       });
//     });
//   };
//   return {
//     Token,
//     info,
//     setInfo,
//     login,
//     getUserInfo,
//   };
// });
